//删除的id
var delId = [];
//	时间初试化
$('#startTime').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
$('#endTime').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
/*$('#createTime').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});*/
$('#orderDate').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
$('#shipmentDate').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
$('#deliverDate').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});

var oprateUrl = DOMAIN + '/CardRecordClear/queryAllList/' + isLogin;

function loadTable() {
	$("#table").bootstrapTable({ // 对应table标签的id
		url: oprateUrl,
		method: 'get',
		cache: false,
		striped: true,
		pagination: true,
		pageSize: 50,
		pageNumber: 1,
		pageList: [50, 100],
		search: false,
		showColumns: false,
		clickToSelect: true,
		queryParams: {
			deleteFlg: 0
		},
		smartDisplay: false,
		columns: [ {
			field: "id",
			title: "id",
			align: "center",
			valign: "middle",
			sortable: "true",
			visible: false
		}, {
			field: "planNo",
			title: "采购计划编号",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "createDateStr",
			title: "创建日期",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "createName",
			title: "创建人",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "statuses",
			title: "状态",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "",
			title: "操作",
			align: "center",
			valign: "middle",
			events: funOprate,
			formatter: function(value, row, index) {
				if (row.deleteFlg == 1) {
					return '<button orderNo="' + row.planNo +
						'" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="EditInfo(this)" class="btn btn-primary btn-sm edit">编辑</button>';
				}
				if (row.statuses == '已确认') {
					return '<button status="' + row.statuses + '"   orderNo="' + row.planNo +
						'" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="lookInfo(this)" class="btn btn-primary btn-sm edit">&emsp;查看</button>  ';
				}
				if (row.statuses == '启用') {
					return '<button status="' + row.statuses + '"   orderNo="' + row.planNo +
						'" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="EditInfo(this)" class="btn btn-primary btn-sm edit">&emsp;编辑</button> <button status="' +
						row.statuses + '"  orderNo="' +
						row.planNo + '" data-del="' + oprateUrl +
						'" onclick="sureInfo(this)" class="btn btn-primary btn-sm">&emsp;确认计划</button></button>';
				} else {
					return '<button status="' + row.statuses + '"   orderNo="' + row.planNo +
						'" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="lookInfoOver(this)" class="btn btn-primary btn-sm edit">&emsp;查看</button> ';
				}
			}
		}],
		//>>>>>>>>>>>>>>导出excel表格设置
		showExport: true,
		showExport: true,
		//是否显示导出按钮
		buttonsAlign: "left",
		//按钮位置
		exportDataType: 'all',
		//导出的方式 all全部 selected已选择的  basic', 'all', 'selected'.
		Icons: 'glyphicon glyphicon-export',
		exportTypes: ['excel', 'doc', 'xlsx', 'txt', ],
		//导出文件类型
		exportOptions: {
			ignoreColumn: [0, 0], //忽略某一列的索引，id删除更新用用，不显示与导出

			fileName: '导出数据表',
			//文件名称设置
			worksheetName: 'sheet1',
			//表格工作区名称
			tableName: '导出数据表',
			// excelstyles: ['background-color', 'color', 'font-size', 'font-weight'], 设置格式

		},
		//导出excel表格设置<<<<<<<<<<<<<<<<
		formatNoMatches: function() {
			return '没有找到匹配的记录';
		}
	});

	function queryParams(params) {
		var params = {};
		return params;
	};
}

//查询
$("#selectPurchaseBtn").click(function() {
	//新查询参数
	function queryParamNew(params) {
		var params = {};
		params.startTime = $("#startTime").val();
		params.endTime = $("#endTime").val();
		// params.customerName = $("#customerName").val();
		params.statuses = $("#status option:checked").val();
		return params;
	};
	var url = DOMAIN + '/CardRecordClear/queryAllList/' + isLogin;
	$('#table').bootstrapTable(
		'refreshOptions', {
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
})

function queryParams(params) {
	return params;
};

//新增按钮，不存到数据库
$("#AddPur-insertBtn").click(function() {

	//获取数据
	var productCode = $('#productCode').val();
	var productName = $('#productName').val();
	//判断商品是否已在明细中
	var rows = $('#tableAddDetail').bootstrapTable('getData');
	for (var i = 0; i < rows.length; i++) {
		if (rows[i].productCode == productCode) {
			alert("商品" + productName + "已经存在，请输入其他商品");
			return;
		}
	}
	var productType = $('#productType').val();
	var specifications = $('#specifications').val();
	var grade = $('#grade').val();
	var units = $('#units').val();
	var amount = $('#amount').val();
	var price = $('#price').val();
	var priceType = $('#priceType').val();
	var roughWeight = $('#roughWeight').val();
	var suttle = $('#suttle').val();
	var comments = $('#comments').val();
	var money = $('#money').val();

	var count = $('#tableAddDetail').bootstrapTable('getData').length;
	var options = $("#tableAddDetail").bootstrapTable('getOptions');
	var pid = options.pageSize * (options.pageNumber - 1) + Number(count) + 1;
	//var t = $('#info').serializeArray();
	var t = getFormJsonObject($("#info"));
	var flag = false;
	var flag = isInfoNull(t);
	if (!flag) {
		return;
	}
	$('#tableAddDetail').bootstrapTable('insertRow', {
		index: count,
		row: {
			pid: pid,
			name: productName,
			productCode: productCode,
			productType: productType,
			specifications: specifications,
			grade: grade,
			units: units,
			price: price,
			priceType: priceType,
			planAmount: amount,
			roughWeight: roughWeight,
			suttle: suttle,
			comments: comments,
			money: money
		}
	});
	//新增后置空
	$('#productCode').val('');
	$('#productName').val('');
	$('#productType').val('');
	$('#specifications').val('');
	$('#grade').val('');
	$('#units').val('');
});






//删除选中行
$("#AddPur-deleteBtn").click(function() {
	var ids = $("#tableAddDetail").bootstrapTable('getSelections')
	if (ids == "" || ids == null) {
		alert("请选中一行");
	} else {
		for (var i = 0; i < ids.length; i++) {
			var pid = ids[i].pid;
			var id = ids[i].id;
			//如果是库中的数据会有id，按照id删除，否则按照序号删除

			if (id == "" || id == null) {
				$("#tableAddDetail").bootstrapTable('remove', {
					field: 'pid',
					values: [pid]
				});
			} else {
				$("#tableAddDetail").bootstrapTable('remove', {
					field: 'id',
					values: [id]
				});
				delId.push(id);
			}

		}

	}
});


$("#insert-pur").click(function() {
	$.ajax({
		type: "patch",
		url: DOMAIN + '/CardRecordClear/queryAllListPlan/' + isLogin,
		dataType: 'JSON',
		contentType: "application/JSON; charset=utf-8",
		success: function(result) {
			if (result.status == 200) {
				alert("生成采购计划成功");
				$("#table").bootstrapTable("refresh", {
					silent: true //静态刷新
				});
			}
			if (result.status == 500) {
				alert("暂无可生成的订单计划");
			}
		},
		error: function() {
			alert('暂无可生成的订单计划');
		},

	});
});


function isInfoNull(t) {

	if (t.productName == '' || t.productName == null) {
		alert("产品名称不能为空");
		return false;
	}
	if (t.price == '' || t.price < 0) {
		alert("商品单价必须大于零");
		return false;
	}
	if (t.priceType == '' || t.priceType == null) {
		alert("价格类型不能为空");
		return false;
	}
	if (t.suttle == '' || t.suttle < 0) {
		alert("产品净重必须大于零");
		return false;
	}
	return true;
}
var info;
//编辑信息
function EditInfo(e) {
	$("#info").css("display","block");
	$("#info-btn").css("display","block");
	$('#tableAddDetail').bootstrapTable('removeAll');
	//将删除的id置空
	delId = [];
/* 	var tableAddDetail = document.getElementById("tableAddDetail");
	tableAddDetail.style.display = "block";

	var tableAddpush = document.getElementById("tableAddpush");
	tableAddpush.style.display = "none"; */

	function queryParamNew(params) {
		var params = {};
		return params;
	};
	info = e;
	var saleNo = $(e).attr('orderNo');
	var url = DOMAIN + '/CardRecordClear/queryListPlan/' + isLogin + '&saleNo=' + saleNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh', {
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
	
}

function delInfo(e) {
	var r = confirm("确定删除该计划吗,删除之后数据将不能恢复？");
	var planNo = $(e).attr('orderNo');
	if (r) {
		$.ajax({
			type: "GET",
			url: DOMAIN + '/CardRecordClear/deleteListPlan/' + isLogin + '&planNo=' + planNo,
			cache: false,
			async: false,
			success: function(data) {
				alert("删除成功！");
				if ($("#tableApproach")) {
					$("#tableApproach").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
				$("#table").bootstrapTable("refresh", {
					silent: true //静态刷新
				});
			}
		});
	}
}


function lookInfo(e) {
	
	$("#info").css("display","none");
	$("#info-btn").css("display","none");
	$('#tableAddDetail').bootstrapTable('removeAll');
	//将删除的id置空
	delId = [];

	function queryParamNew(params) {
		var params = {};
		return params;
	};
/* 	var tableAddDetail = document.getElementById("tableAddDetail");
	tableAddDetail.style.display = "none";

	var tableAddpush = document.getElementById("tableAddpush");
	tableAddpush.style.display = "block"; */
	var saleNo = $(e).attr('orderNo');
	var url = DOMAIN + '/CardRecordClear/queryListPlanDel/' + isLogin + '&saleNo=' + saleNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh', {
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);

}

function lookInfoOver(e) {
	
	$("#info").css("display","none");
	$("#info-btn").css("display","none");
	$('#tableAddDetail').bootstrapTable('removeAll');
	//将删除的id置空
	delId = [];

	function queryParamNew(params) {
		var params = {};
		return params;
	};
/* 	var tableAddDetail = document.getElementById("tableAddDetail");
	tableAddDetail.style.display = "none";

	var tableAddpush = document.getElementById("tableAddpush");
	tableAddpush.style.display = "block"; */
	var saleNo = $(e).attr('orderNo');
	var url = DOMAIN + '/CardRecordClear/queryListPlanDelOver/' + isLogin + '&saleNo=' + saleNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh', {
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);

}

function sureInfo(e) {
	var planNo = $(e).attr('orderNo');
	var r = confirm("确认该计划后将无法修改,确定操作吗？");
	if (r) {
		$.ajax({
			type: "GET",
			url: DOMAIN + '/CardRecordClear/sureListPlan/' + isLogin + '&planNo=' + planNo,
			cache: false,
			async: false,
			success: function(data) {
				//alert("计划已确认！");
				if ($("#tableApproach")) {
					$("#tableApproach").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
				$("#table").bootstrapTable("refresh", {
					silent: true //静态刷新
				});
			}
		});
	}
}

//保存单条信息
function saveInfo(e) {
	$('#tableAddDetail').bootstrapTable('removeAll');
	//将删除的id置空
	delId = [];

	function queryParamNew(params) {
		var params = {};
		return params;
	};
	var saleNo = $(e).attr('orderNo');
	var url = DOMAIN + '/CardRecordClear/queryListPlan/' + isLogin + '&saleNo=' + saleNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh', {
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
}

//新增前填写日期并获取批次号与进货编号


function getFormJsonObject($form) {
	var unindexed_array = $form.serializeArray();
	var indexed_array = {};

	$.map(unindexed_array, function(n, i) {
		indexed_array[n['name']] = n['value'];
	});

	return indexed_array;
};

//计算行金额
function calc() {
	var r_price = $("#price").val();
	var r_amount = $("#amount").val();
	if (r_price != "" && r_price > 0 && r_amount > 0 && r_amount != "") {
		$("#money").val(r_price * r_amount);
	} else {
		$("#money").val(0);
	}
}

//打开选择框时查询
$('#myModal').on('shown.bs.modal', function() {
	//getSelList($("#purchaseType1"), "/v1/purchaseType" + isLogin);
	$('#tableAddDetail').bootstrapTable(
		'refreshOptions', {
			//url: DOMAIN+'/v1/salesOrder'+isLogin,
		}
	);

})

//保存
$("#AddPur-saveBtn").click(function() {
	//得到新增表格数据
	var params = getDataForAdd();
	var flag = false;
	var flag = isMainNull(params);
	if (!flag) {
		//alert("请先输入数据");
		return;
	}
	var saleNo = $(info).attr('orderNo');
	params.planNo = saleNo;
	var list = params.warehouseOutInfoList;
	params = JSON.stringify(params);
	list = JSON.stringify(list);
	//进货id是否绑定,没有id就新增
	console.log(params);
	if (saleNo == '' || saleNo == null) {
		$.ajax({
			type: "post",
			url: DOMAIN + '/CardRecordClear/insertPlan/' + isLogin,
			data: params,
			dataType: 'JSON',
			contentType: "application/JSON; charset=utf-8",
			success: function(result) {
				if (result.status == 200) {
					alert("保存成功");
					$("#table").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
			},
			error: function() {
				alert('保存失败');
			}
		});
		// $('#main1')[0].reset();
		//$('#info')[0].reset();
		$('.close').click();
	} else {
		//更新
		$.ajax({
			type: "patch",
			url: DOMAIN + '/CardRecordClear/insertPlanInfo/' + isLogin,
			data: params,
			dataType: 'JSON',
			contentType: "application/JSON; charset=utf-8",
			success: function(result) {
				if (result.status == 200) {

					alert("保存成功");
					$("#table").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
			},
			error: function() {
				alert('编辑失败');
			},
			complete: function() {}
		});
		//$('#info')[0].reset();
		$('#mainId').val('');
		$('.close').click();
		//将删除的id置空
		delId = [];
		saleNo = null;
		
	}
});



/* //保存
$("#AddPur-saveBtn").click(function() {
	//得到新增表格数据
	var params = getDataForAdd();
	var flag = false;
	var flag = isMainNull(params);
	if (!flag) {
		//alert("请先输入数据");
		return;
	}
	var saleNo = $(info).attr('orderNo');
	params.planNo = saleNo;
	params = JSON.stringify(params);
	//进货id是否绑定,没有id就新增
	//更新
	$.ajax({
		type: "patch",
		url: DOMAIN + '/CardRecordClear/insertPlanInfo/' + isLogin,
		data: params,
		dataType: 'JSON',
		contentType: "application/JSON; charset=utf-8",
		success: function(result) {
			if (result.status == 200) {

				alert("保存成功");
				$("#table").bootstrapTable("refresh", {
					silent: true //静态刷新
				});
			}
		},
		error: function() {
			alert('编辑失败');
		},
		complete: function() {}
	});
	$('#info')[0].reset();
	$('#mainId').val('');
	$('.close').click();
	//将删除的id置空
	delId = [];

}); */


//关闭
$("#AddPur-closeBtn").click(function() {
	$("#close-btn")[0].click();
})

var flag = "";

function sign() {
	flag = "customer";
}

function sign2() {
	flag = "customerAdd";
}

function selectCustomer(row) {
	if (flag == "customer") {
		$("#customerName").val(row.name);
	}
	if (flag = "customerAdd") {
		$("#customerNameAdd").val(row.name);
		$("#customerNo").val(row.code);
	}
}

function selectProduct(row) {
	$("#productName").val(row.name);
	$("#productCode").val(row.code);
	$("#productType").val(row.levelOneName + "/" + row.levelTwoName);
	$("#specifications").val(row.specifications);
	$("#grade").val(row.gradeName);
	$("#units").val(row.units);
}
$("#tableAddDetail").bootstrapTable({ // 对应table标签的id
	url: "",
	method: 'get',
	cache: false,
	striped: true,
	pagination: true,
	pageSize: 200,
	pageNumber: 1,
	pageList: [200, 500],
	search: false,
	showColumns: false,
	clickToSelect: true,
	queryParams: queryParams,
	smartDisplay: false,
	columns: [{
			checkbox: true
		},
		{
			field: "id",
			title: "id",
			align: "center",
			valign: "middle",
			sortable: "true",
			visible: false
		},
		{
			field: "pid",
			title: "序号",
			align: "center",
			valign: "middle",
			sortable: "true",
			visible:false
		}, {
			field: "name",
			title: "产品名称",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "units",
			title: "单位",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "sumAmount",
			title: "客户需求量",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "recommendAmount",
			title: "推荐采购量",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "planAmount",
			title: "计划采购量",
			align: "center",
			valign: "middle",
			sortable: "true",
			formatter: function(value, row, index) {
				if (isEmpty(row.planAmount)) {
					row.planAmount = row.sumAmount;
				}
				return row.planAmount;
			},
			cellStyle: function(value, row, index) {
				return {
					css: {
						"color": "#0088cc"
					}
				}
			}
		}, {
			field: "completed",
			title: "已完成量",
			align: "center",
			valign: "middle",
			sortable: "true"
		},
		{
			field: "undone",
			title: "未完成量",
			align: "center",
			valign: "middle",
			sortable: "true",
			formatter: function(value, row, index) {
			
				return row.undone.toFixed(2);
			}
		}
	],
	formatNoMatches: function() {
		return '';
	},
	onClickCell: function(field, value, row, $element) {
		if (field == "planAmount") {
			$element.attr('contenteditable', true);
			$element.blur(function() {
				if ($element.html() == "" || isNaN($element.html())) {
					$element.html(value);
				} else {
					let index = $element.parent().data('index');
					let tdValue = $element.html();
					saveData(index, field, tdValue, row);
				}
			});
		}
	}
});


function saveData(index, field, value, row) {
	$("#tableAddDetail").bootstrapTable('updateCell', {
		index: index,
		field: field, //列名
		value: value //cell值
	});

	$("#tableAddDetail").bootstrapTable('updateCell', {
		index: index,
		field: 'undone', //列名
		value: value - row.completed //cell值
	});
	var dict = JSON.stringify(row);
	id = row.id;
	planAmount = value;
	$.ajax({
		type: "patch",
		url: DOMAIN + '/CardRecordClear/updatePlanInfo/' + isLogin + '&id=' + id + '&planAmount=' + planAmount,
		dataType: 'JSON',
		contentType: "application/JSON; charset=utf-8",
		success: function(result) {
			if (result.status == 200) {
				$("#table").bootstrapTable("refresh", {
					silent: true //静态刷新
				});
			}
		},
		complete: function() {}
	});
}

function isMainNull(t) {
	return true;
}

function isInfoNull(t) {

	if (t.productName == '' || t.productName == null) {
		alert("产品名称不能为空");
		return false;
	}
	if (t.price == '' || t.price < 0) {
		alert("商品单价必须大于零");
		return false;
	}
	if (t.priceType == '' || t.priceType == null) {
		alert("价格类型不能为空");
		return false;
	}
	if (t.suttle == '' || t.suttle < 0) {
		alert("产品净重必须大于零");
		return false;
	}
	return true;
}

//新增时获取数据的方法
function getDataForAdd() {
	var rows = $('#tableAddDetail').bootstrapTable('getData');
	var params = {};
	params.productName = $("#productName").val();
	params.price = $("#price").val();
	params.sumAmount = $("#amount").val();
	params.planAmount = $("#amount").val();
	params.money = $("#money").val();
	params.warehouseOutInfoList = rows;
	params.delId = delId;
	return params;

}

//新增前填写日期并获取批次号与进货编号
function resetTable() {
	// 将删除的id置空
	delId = [];
	$('#main1')[0].reset();
	//$('#info')[0].reset();
	time_rota($("#createTime"));
	$('#tableAddDetail').bootstrapTable('removeAll');
}

function getFormJsonObject($form) {
	var unindexed_array = $form.serializeArray();
	var indexed_array = {};

	$.map(unindexed_array, function(n, i) {
		indexed_array[n['name']] = n['value'];
	});

	return indexed_array;
};

//计算行金额
function calc() {
	var r_price = $("#price").val();
	var r_amount = $("#amount").val();
	if (r_price != "" && r_price > 0 && r_amount > 0 && r_amount != "") {
		$("#money").val(r_price * r_amount);
	} else {
		$("#money").val(0);
	}
}

//下拉框填充
$(function() {

	loadTable();
	getSelList2($("#status"), "plan_status");
	/*getSelList($("#orderType"), "sale_order_type");
	getSelList($("#deliverType"), "deliver_type");
	getSelList($("#payType"), "count_way");*/

	$("#deliverType").on("change", function() {
		var deliver_type = $("#deliverType option:checked").html();
		if (deliver_type == "自提") {
			$("#addressDiv").css("display", "none");
			$("#address").val("");
		} else {
			$("#addressDiv").css("display", "block");
		}
	});

	$("#price").on("blur", function() {
		calc();
	});

	$("#amount").on("blur", function() {
		calc();
	});
	
	time_rota2($('#startTime'));
	time_rota($('#endTime'));
	//新查询参数
	function queryParamNew(params) {
		var params = {};
		params.startTime = $("#startTime").val();
		params.endTime = $("#endTime").val();
		return params;
	};
	var url = DOMAIN + '/CardRecordClear/queryAllList/' + isLogin;
	$('#table').bootstrapTable(
		'refreshOptions', {
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
})

//打开选择框时查询
$('#myModal').on('shown.bs.modal', function() {
	//getSelList($("#purchaseType1"), "/v1/purchaseType" + isLogin);
	$('#tableAddDetail').bootstrapTable(
		'refreshOptions', {
			//url: DOMAIN+'/v1/salesOrder'+isLogin,
		}
	);

})

//关闭
$("#AddPur-closeBtn").click(function() {
	$("#close-btn")[0].click();
})

var flag = "";

function sign() {
	flag = "customer";
}

function sign2() {
	flag = "customerAdd";
}

function selectCustomer(row) {
	if (flag == "customer") {
		$("#customerName").val(row.name);
	}
	if (flag = "customerAdd") {
		$("#customerNameAdd").val(row.name);
		$("#customerNo").val(row.code);
	}
}

function selectProduct(row) {
	$("#productName").val(row.name);
	$("#productCode").val(row.code);
	$("#productType").val(row.levelOneName + "/" + row.levelTwoName);
	$("#specifications").val(row.specifications);
	$("#grade").val(row.gradeName);
	$("#units").val(row.units);
}
